package com.minshenglife.zanzan.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.minshenglife.commons.dal.Page;
import com.minshenglife.zanzan.dao.EndPlateDao;
import com.minshenglife.zanzan.dao.UserDao;
import com.minshenglife.zanzan.entity.EndPlate;
import com.minshenglife.zanzan.entity.User;
import com.minshenglife.zanzan.pub.CalcUtils;
import com.minshenglife.zanzan.result.EndPlateResult;
import com.minshenglife.zanzan.service.EndPlateService;


/**
 * 吐槽service
 * @author huodd
 *
 */
@Component
@Transactional
public class EndPlateServiceImpl  implements EndPlateService {
	Logger log = LoggerFactory.getLogger(EndPlateServiceImpl.class);
	@Resource
	private EndPlateDao endPlateDao;
	@Resource
	private UserDao userDao;
	/**
	 * 吐槽列表
	 */
	@Override
	public Page<EndPlateResult> findEndPlateInfo(Map<String,Object> map,int pageNo,int pageSize){
		if(map==null)
			map=new HashMap<String,Object>();
		int offset = (pageNo-1) * pageSize;
        Long count =endPlateDao.countByParams(map);
        map.put("from", offset);
        map.put("to", offset+pageSize);
        List<EndPlateResult> rows =endPlateDao.findEndPlateInfo(map);
        Page<EndPlateResult> epr = new Page<EndPlateResult>();
        epr.setRows(rows);
        epr.setTotalRow(count);
        epr.setTotalPage(CalcUtils.calcTotalPage(pageSize, count));
        epr.setPageSize(pageSize);
        epr.setPageNo(pageNo);
        return epr;
	}
	
	/**
	 * 吐槽
	 */
	@Override
	public void insertUserEndPlate(EndPlate endPlate,Boolean isNotLimit) {
		log.debug("start insert endPlate info");
		endPlateDao.insertUserEndPlate(endPlate);
		if(isNotLimit){//无限制吐槽时，无需更新用户信息
			User user=userDao.getUserByUserId(endPlate.getEmpId());
			user.setCanTuCaoNum(user.getCanTuCaoNum()-1);
			log.debug("start update user CanTuCaoNum :"+user.getCanTuCaoNum());
			userDao.update(user);
		}
		log.debug("end insert endPlate info");
	}

	@Override
	@Transactional(readOnly=true)
	public EndPlateResult getEndPlateInfoById(String id) {
		log.debug("========"+Long.parseLong(id));
		EndPlateResult result=endPlateDao.getEndPlateInfoById(new EndPlate(Long.parseLong(id)));
		return result;
	}

	@Override
	public int updateEndPlatePraiseNum(String id, int num) {
		log.info("start updateEndPlatePraiseNum() ");
		EndPlate e=endPlateDao.get(Long.parseLong(id));
		int a = 0;
		if(null!=e&&null!=e.getPraiseNum()){
			a=Integer.parseInt(e.getPraiseNum());
		}
		num+=a;
		e.setPraiseNum(String.valueOf(num));
		log.debug("更新被赞的数量是："+String.valueOf(num));
		endPlateDao.update(e);
		log.info("end updateEndPlatePraiseNum() ");
		return num;
	}


}
